package org.budo.graph.service.impl;

import java.io.File;

import org.budo.support.application.registry.BudoApplicationUtil;
import org.budo.support.lang.util.FileUtil;
import org.budo.support.lang.util.IoUtil;
import org.budo.support.lang.util.SystemUtil;
import org.budo.time.Time;
import org.springframework.beans.factory.InitializingBean;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class WriteHealthzScriptServiceImpl implements InitializingBean {
    private void writeHealthzScript() {
        log.info("#21 writeHealthzScript, this=" + this);

        if (SystemUtil.isMac()) {
            log.warn("#41 isMac, return, " + SystemUtil.getOsName() + ", " + this);
            return;
        }

        String applicationName = BudoApplicationUtil.getApplicationName();
        if (null == applicationName || applicationName.trim().isEmpty()) {
            log.error("#31 budoGraphService is null, this=" + this);
            return;
        }

        File fileTo = new File("/.budo.healthz/" + applicationName);
        if (fileTo.exists()) {
            log.warn("#37 to exists, applicationName=" + applicationName + ", canonicalPath=" + FileUtil.getCanonicalPath(fileTo));
        }

        IoUtil.write("echo \"hello healthz started at " + Time.now().toString("yyyyMMdd.HHmmss.SSS") + "\"", fileTo);

        log.warn("#47 after write file, applicationName=" + applicationName + ", canonicalPath=" + FileUtil.getCanonicalPath(fileTo));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            this.writeHealthzScript();
        } catch (Throwable e) {
            log.error("#26 writeHealthzScript error, e=" + e, e);
        }
    }
}